import React, { Component } from 'react'
import { Layout, Tabs, message } from 'antd'
import InnerHeader from '../layout/product_header'
import './product.sass'
import ProductStyle from './product.module.sass'
import ProductName from '../common/details/product_details'
import Performance from '../common/details/performance'
import Hold from '../common/details/hold'
import Analysis from '../common/details/analysis'
import Scene from '../common/details/scene'
import Infos from '../common/details/infos'
import { axios } from '../../Utils/index'
import url from 'url'
import cookie from 'js-cookie'
import { exportDetailsExcel } from '../../apis/index'
import moment from 'moment'
import 'moment/locale/zh-cn'
moment.locale('zh-cn')

const { Sider, Content } = Layout
const TabPane = Tabs.TabPane

export default class Product extends Component {
    constructor (props) {
        super(props)
        this.state = {
            noTitleKey: 'performance',
            collapsed: true,
            collapasedTrigger: null,
            collapasedWidth: 0,
            tabList: []
        }
    }

    componentDidMount () {
        document.getElementsByTagName('body')[0].setAttribute('class', 'product-wrapper product_details')
        const { query } = url.parse(window.location.href, true)
        if (query.name) {
            window.localStorage.setItem('productName', decodeURI(query.name))
        }
    }

    async _exportAndDownload () {
        const { query } = url.parse(window.location.href, true)
        let parmas = {
            "token": cookie.get('token'),
            "fundName": window.localStorage.getItem('productName'),
            "modules":
                [
                    {
                        "moduleName":"业绩表现",
                        "moduleContent":
                            [
                                {
                                    "tableOrChartName":"收益走势图",
                                    "tableOrChartCode":"returnCal",
                                    "tableOrChartParams":
                                        {
                                            "startLine":"0",
                                            "dateRange":"2018-01-01:2019-01-01",
                                            "fundIds": query.id,
                                            "navType":"n_nav",
                                            "compareRule":"0"
                                        }
                                },
                                {
                                    "tableOrChartName":"回撤走势图",
                                    "tableOrChartCode":"drawdownCal",
                                    "tableOrChartParams":
                                        {
                                            "startLine":"0",
                                            "dateRange":"2018-01-01:2019-01-01",
                                            "fundIds": query.id,
                                            "navType":"n_nav",
                                            "compareRule":"0"
                                        }
                                },
                                {
                                    "tableOrChartName":"收益-风险指标",
                                    "tableOrChartCode":"riskIndicator",
                                    "tableOrChartParams":
                                        {
                                            "funds":
                                                [
                                                    {
                                                        "fundId": query.id,
                                                        "fundName": window.localStorage.getItem('productName'),
                                                        "interval":"year"
                                                    },
                                                    {
                                                        "fundId":"JR000002",
                                                        "fundName": window.localStorage.getItem('productName'),
                                                        "interval":"year"
                                                    }
                                                ]
                                        }
                                },
                                {
                                    "tableOrChartName":"月度收益率",
                                    "tableOrChartCode":"monthReturn",
                                    "tableOrChartParams":
                                        {
                                            "token":"99a27d12-657b-4850-8c61-1c69fa8dbee6",
                                            "fund_id": query.id
                                        }
                                },
                                {
                                    "tableOrChartName":"周收益率分布",
                                    "tableOrChartCode":"weekReturn",
                                    "tableOrChartParams":
                                        {
                                            "fund_id": query.id,
                                            "compare_fund_id":"JR000028",
                                            "beginTime":"971107200",
                                            "endTime":"1602259200"
                                        }
                                },
                                {
                                    "tableOrChartName":"产品相关性",
                                    "tableOrChartCode":"productCorrelation",
                                    "tableOrChartParams":
                                        {
                                            "fund_id": query.id,
                                            "c_interval":"year",
                                            "c_cor_ids":
                                                [
                                                    "COR000001","COR000002"
                                                ]
                                        }
                                }
                            ]
                    },
                    {
                        "moduleName":"持仓信息",
                        "moduleContent":
                            [
                                {
                                    "tableOrChartType":"股票多头",
                                    "tableOrChartName":"仓位总览",
                                    "tableOrChartCode":"inventoryOverview",
                                    "tableOrChartParams":
                                        {
                                            "fundId": "JR000014",
                                            "startDate": "2014-01-01",
                                            "endDate": "2015-01-01"
                                        }
                                },
                                {
                                    "tableOrChartType":"股票多头",
                                    "tableOrChartName":"板块配置",
                                    "tableOrChartCode":"tectonic",
                                    "tableOrChartParams":
                                        {
                                            "fundId": "JR000002",
                                            "beginTime": "971107200",
                                            "endTime": "1602259200"
                                        }
                                },
                                {
                                    "tableOrChartType":"股票多头",
                                    "tableOrChartName":"行业集中度",
                                    "tableOrChartCode":"industryConcentration",
                                    "tableOrChartParams":
                                        {
                                            "fundId":"JR000001",
                                            "beginTime":"971107200",
                                            "endTime":"1602259200"
                                        }
                                },
                                {
                                    "tableOrChartType":"期货",
                                    "tableOrChartName":"仓位总览",
                                    "tableOrChartCode":"forwardInventoryOverview",
                                    "tableOrChartParams":
                                        {
                                            "fundId": "JR000001",
                                            "startDate": "2014-01-01",
                                            "endDate": "2015-01-01"
                                        }
                                },
                                {
                                    "tableOrChartType":"期货",
                                    "tableOrChartName":"板块配置",
                                    "tableOrChartCode":"tectonicFutures",
                                    "tableOrChartParams":
                                        {
                                            "fundId":"JR000001",
                                            "beginTime":"971107200",
                                            "endTime":"1602259200"
                                        }
                                },
                                {
                                    "tableOrChartType":"期货",
                                    "tableOrChartName":"资产配比(饼图)",
                                    "tableOrChartCode":"varietyPie",
                                    "tableOrChartParams":
                                        {
                                            "fundId":"JR000001",
                                            "tDate":"1339084800"
                                        }
                                },
                                {
                                    "tableOrChartType":"期货",
                                    "tableOrChartName":"资产配比(柱状图)",
                                    "tableOrChartCode":"varietyBar",
                                    "tableOrChartParams":
                                        {
                                            "fundId":"JR000001",
                                            "tDate":"1339084800"
                                        }
                                }
                            ]
                    }
                ]
        }
        message.loading('正在下载报告，请稍等！')
        const exportData = await exportDetailsExcel(parmas)

        if (exportData.status === 'success') {
            const json = JSON.parse(exportData.result)
            let url = `${process.env.REACT_APP_EXPORT_URL}hszcpz/exportExcel/exportProductExcelFile/?token=${cookie.get('token')}&fileName=${json.fileName}&fileDate=${json.fileDate}`

            window.location.href = url
        }
    }

    onTabChange = (key, type) => {
        this.setState({ [type]: key })
    }

    componentWillUnmount () {
        document.getElementsByTagName('body')[0].setAttribute('class', '')
    }

    async _getReturnCal (params) {
        const { query } = url.parse(window.location.href, true)
        const data = await axios({
            url: '/api/hszcpz/product/getReturnCal',
            method: 'POST',
            data: JSON.stringify({
                fundIds: query.id,
                token: cookie.get('token'),
                startLine: 0,
                navType: 'n_added_nav',
                dateRange: '2019-01-01:2019-12-31',
                compareRule: '0',
                ...params
            })
        })

        message.destroy()
        if (!data.hasOwnProperty('status')) {
            message.info('接口获取数据失败')
            return
        }

        this.setState({loading: false})
        if (data.status !== 'success') {
            message.info(data.errorReason)
            return
        }
        if (!data.hasOwnProperty('result')) {
            message.info('接口获取数据失败')
            return
        }
        
        let result = data.result

        if (data.status === 'success') {
            return result
        } else {
            message.error('获取数据失败')
        }

    }


    async _getDrawdownCal (params) {
        const { query } = url.parse(window.location.href, true)
        const data = await axios({
            url: '/api/hszcpz/product/getDrawdownCal',
            method: 'POST',
            data: JSON.stringify({
                fundIds: query.id,
                token: cookie.get('token'),
                startLine: 0,
                navType: 'n_added_nav',
                dateRange: '2019-01-01:2019-12-31',
                compareRule: '0',
                ...params
            })
        })

        message.destroy()
        if (!data.hasOwnProperty('status')) {
            message.info('接口获取数据失败')
            return
        }

        this.setState({loading: false})
        if (data.status !== 'success') {
            message.info(data.errorReason)
            return
        }
        if (!data.hasOwnProperty('result')) {
            message.info('接口获取数据失败')
            return
        }

        let result = data.result

        if (data.status === 'success') {
            return result
        } else {
            message.error('获取数据失败')
        }
    }


    async _initData () {
        const { query } = url.parse(window.location.href, true)
        const data = await axios({
            url: '/api/hszcpz/product/init',
            method: 'POST',
            data: JSON.stringify({
                fund_id: query.id,
                token: cookie.get('token'),
                c_interval: 'm3'
            })
        })

        message.destroy()
        if (!data.hasOwnProperty('status')) {
            message.info('接口获取数据失败')
            return
        }

        this.setState({loading: false})
        if (data.status !== 'success') {
            message.info(data.errorReason)
            return
        }
        if (!data.hasOwnProperty('result')) {
            message.info('接口获取数据失败')
            return
        }

        let result = JSON.parse(data.result)

        if (result.result === 'success') {
            this.setState({productInfo: result.product})
            return result.product
        }
    }

    toggleWidth = () => {
        let siderWidth = this.state.collapasedWidth

        if (siderWidth === 0) {
            this.setState({
                collapasedWidth: 200
            })
        } else {
            this.setState({
                collapasedWidth: 0
            })
        }
    }

    render () {

        return(
            <div className={ProductStyle.product_wrapper}>
                <Layout>
                    <Sider className={ProductStyle.sider_left} theme='light' trigger={this.state.collapasedTrigger} collapsedWidth={this.state.collapasedWidth} collapsible={true} collapsed={this.state.collapsed}>

                    </Sider>
                    <Layout>
                        <InnerHeader />
                        <Content className={ProductStyle.details_container}>
                            <ProductName productInfo = {this._initData.bind(this)} _report={this._exportAndDownload.bind(this)} />
                            <Tabs defaultActiveKey="1" className={`tabs_items`}>
                                <TabPane className={`tabs_item`} tab="业绩表现" key="1">
                                    <Performance _getReturnCal={this._getReturnCal.bind(this)} _getDrawdownCal={this._getDrawdownCal.bind(this)}  />
                                </TabPane>
                                <TabPane className={`tabs_item`} tab="持仓信息" key="2">
                                    <Hold />
                                </TabPane>
                                <TabPane className={`tabs_item`} tab="归因分析" key="3">
                                    <Analysis />
                                </TabPane>
                                <TabPane className={`tabs_item`} tab="场景分析" key="4">
                                    <Scene />
                                </TabPane>
                                <TabPane className={`tabs_item`} tab="产品信息" key="5">
                                    <Infos />
                                </TabPane>
                            </Tabs>
                        </Content>
                    </Layout>
                </Layout>
           </div>
        )
    }
}
